<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>
        通过点击绘制顶点并改变颜色
    </title>
</head>

<body onload="main()">
<canvas id="example" width="400" height="400" style="border: 1px solid red;"> canves</canvas>
<script src="../js/cuon-utils.js"></script>
<script src="../js/webgl-debug.js"></script>
<script src="../js/webgl-utils.js"></script>
<script>
    // 顶点着色器
    // 'attribute float a_PointSize;' +
    var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' +
        ' void main() {\n' +
        ' gl_Position = a_Position;\n' + // 设置坐标
        ' gl_PointSize = 10.0;\n' +// 设置尺寸
        '}\n';

    // 片元着色器
    var FSHADER_SOURCE =
        'precision mediump float;' +
        'uniform vec4 u_FragColor;' +
        'void main() {\n' +
        ' gl_FragColor = u_FragColor;\n' + // 设置颜色
        '}\n';

    function main() {

        var canves = document.getElementById("example");

        var gl = getWebGLContext(canves);

        // 初始化着色器
        if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
            console.error("着色器加载错误")
            return;
        }

        // 获取attribute变量存储的位置
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');

        if (a_Position < 0) {
            console.error("参数错误")
            return;
        }

        // 将顶点变量传给attribute变量
        gl.vertexAttrib1f(a_Position, 0.0);

        gl.clearColor(0.0, 1.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        gl.drawArrays(gl.POINTS, 0, 1);

        canves.onmousedown = function (ev) {
            click(ev, gl, canves, a_Position, u_FragColor);
        }
    }

    var g_points = [];
    var g_colors = [];

    function click(ev, gl, canvas, a_Position, u_FragColor) {
        var x = ev.clientX;
        var y = ev.clientY;

        var rect = ev.target.getBoundingClientRect();

        x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2);
        y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2)

        g_points.push([x, y])

        if (x >= 0 && y >= 0) {
            g_colors.push([1.0, 0.0, 0.0, 1.0])
        } else {
            g_colors.push([0.0, 0.0, 1.0, 1.0])
        }

        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;
        console.log("len", len)
        for (var i = 0; i < len; i++) {
            console.log("g_points", g_points[i])
            gl.vertexAttrib2f(a_Position, g_points[i][0], g_points[i][1])
            gl.uniform4f(u_FragColor, g_colors[i][0], g_colors[i][1], g_colors[i][2], g_colors[i][3])
            gl.drawArrays(gl.POINTS, 0, 1)
        }
    }

</script>
</body>

</html>